package com.xinchao.ck_mips.utils;

import android.util.Log;

import com.orhanobut.logger.Logger;
import com.xinchao.ck_mips.base.CKSubscriber;
import com.xinchao.devicemanage.constant.DeviceConstant;
import com.xinchao.devicemanage.util.DeviceSubscriber;
import com.xinchao.machine.digital_advertise.IBaseMachine;
import com.xinchao.rxtools.rxhttp.tools.IDisposable;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wq on 2019/7/10.
 */
public class WatchDogUtil {
    private IBaseMachine iBaseMachine;
    private IDisposable iDisposable;

    public WatchDogUtil(IBaseMachine iBaseMachine, IDisposable iDisposable) {
        this.iBaseMachine = iBaseMachine;
        this.iDisposable = iDisposable;
        startWatchdog();
    }

    private void startWatchdog() {
        try {
            iBaseMachine.disable_watchdog();
            int stu = iBaseMachine.enable_watchdog();
            if (stu == 1) {
                Log.v("xika", "开启喂狗");
                Logger.t(DeviceConstant.DEVICE_LOG).d("开启看门狗");
                startFeedWatchdog(iDisposable);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startFeedWatchdog(final IDisposable iDisposable) {
        Flowable.timer(30, TimeUnit.SECONDS, Schedulers.io()).subscribe(new CKSubscriber<Long>(iDisposable) {
            @Override
            protected void finish() {
                Log.v("xika", "开始喂狗");
                startFeedWatchdog(iDisposable);
                super.finish();
            }

            @Override
            protected void next(Long aLong) {
                try {
                    iBaseMachine.feed_watchdog();
                    Logger.t(DeviceConstant.DEVICE_LOG).d("20s,喂狗");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
